package com.practice.backend.Controller;

import com.practice.backend.Common.Jwt;
import com.practice.backend.Common.Result;
import com.practice.backend.Entity.LoginHistory;
import com.practice.backend.Entity.User;

import com.practice.backend.Entity.UserSearchCriteria;
import com.practice.backend.Repository.LoginHistoryRepository;
import com.practice.backend.Repository.UserRepository;

import com.practice.backend.Repository.UserSpecification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserRepository userRepository;
    @Autowired
    LoginHistoryRepository loginHistoryRepository;



    //查询所有用户
    @GetMapping("/findAll")
    public Result hello() {
        List<User> users = userRepository.findAll();
        return Result.success(true,"查询成功", users.size(), users);
    }

    //添加用户
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user) {
        System.out.println("user:"+user);
        if (userRepository.findByUsername(user.getUsername())!=null)
            return Result.error(false,"用户名已存在", 0, null);
        if (userRepository.findByPhone(user.getPhone())!=null)
            return Result.error(false,"手机号已存在", 0, null);
        userRepository.save(user);
        return userRepository.findById(user.getId()).isPresent()?Result.success(true,"添加成功", 1, user) : Result.error(false,"添加失败", 0, null);
    }

    //删除用户
    @DeleteMapping("/deleteUserById")
    public Result deleteUser(@Param("id") int id) {
        userRepository.deleteById(id);
        return !userRepository.findById(id).isPresent()?Result.success(true,"删除成功", 1, null) : Result.error(false,"删除失败", 0, null);
    }

    //通过用户名查询用户
    @GetMapping("/findUserByUsername/{username}")
    public User findUserByUsername(@PathVariable String username) {
        return userRepository.findByUsername(username);
    }

    //通过用户名模糊查询用户
    @GetMapping("/findUserByUsernameLike/{username}")
    public List<User> findUserByUsernameLike(@PathVariable("username") String username) {
        return userRepository.findByUsernameContaining(username);
    }

    //修改用户
    @PutMapping("/updateUserById")
    public Result updateUser(@RequestBody User user) {
        System.out.println(user.getSex());
        User saved = userRepository.save(user);
        return saved.toString().equals(user.toString())?Result.success(true,"修改成功", 1, saved) : Result.error(false,"修改失败", 0, null);
    }

    //分页查询所有用户(以result返回)
    //参数：pageNum,pageSize
    @GetMapping("/findAllUserByPage")
    public Result findAllUserByPage(@RequestParam("pageNum") int pageNum,
                                    @RequestParam("pageSize") int pageSize) {

        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<User> pageResult = userRepository.findAll(pageable);

        return Result.success(true,"查询成功", (int) pageResult.getTotalElements(), pageResult.getContent());
    }

    //根据性别分页查询用户
    @GetMapping("/findUserBySexWithPage/{sex}")
    public List<User> findUserBySexWithPage(@PathVariable("sex") String sex,
                                            @RequestParam("pageNum") int pageNum,
                                            @RequestParam("pageSize") int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        return userRepository.findBySex(sex, pageable).getContent();
    }

    //根据条件查询用户
    @GetMapping("/findUserByCondition")
    public Result findUserByCondition(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestParam(value = "id", required = false) String id,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "sex", required = false) String sex,
            @RequestParam(value = "age", required = false) Integer age,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "rankId", required = false) String rankId,
            @RequestParam(value = "status", required = false) String status) {

        UserSearchCriteria criteria = new UserSearchCriteria();
        criteria.setId(id);
        criteria.setUsername(username);
        criteria.setSex(sex);
        criteria.setAge(age);
        criteria.setPhone(phone);

        // 将 rankId 转换为 List<String>
        if (rankId != null && !rankId.isEmpty()) {
            ArrayList<String> rankIdList = new ArrayList<>();
            String[] rankIds = rankId.split(","); // 假设 rankId 是逗号分隔的字符串
            Collections.addAll(rankIdList, rankIds);
            criteria.setRankIds(rankIdList);
        }

        criteria.setStatus(status);

        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<User> page = userRepository.findAll(new UserSpecification(criteria), pageable);
        return Result.success(true, "查询成功", (int) page.getTotalElements(), page.getContent());
    }
    //修改用户状态
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody User user) {
        int id = user.getId();
        String status = user.getStatus();
        user = userRepository.findById(id).get();
        user.setStatus(status);
        User saved = userRepository.save(user);
        return saved.toString().equals(user.toString())?Result.success(true,"修改成功", 1, saved) : Result.error(false,"修改失败", 0, null);
    }

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User findUser = userRepository.findByUsername(user.getUsername());
        if(findUser != null){
            LoginHistory loginHistory = new LoginHistory();
            loginHistory.setToken(Jwt.createJwt(findUser));
            loginHistoryRepository.save(loginHistory);
        }
        return findUser != null && findUser.getPassword().equals(user.getPassword()) ? Result.success(true,"登录成功", 1, findUser) : Result.error(false,"登录失败", 0, null);
    }
    }
